<template>
  <el-dialog
    v-el-drag-dialog
    title="订单审核"
    :visible.sync="visible"
    width="700px"
  >
    <div class="vettingorders">
      <img v-if="overCheck" :src="require('@/assets/noCheck.png')" alt="状态" class="status-img">
      <p class="desc">客户名称：{{ temp.csmName }}({{ temp.contactPhone }})</p>
      <p class="desc">商品描述：{{ temp.goodsDesc }}</p>
      <p class="desc">{{ temp.csmAddress }}</p>
      <p v-if="lastOrderInfo.orgName" class="desc">上次订气处理部门：{{ lastOrderInfo.orgName }}<span v-if="lastOrderInfo.lastSender">({{ lastOrderInfo.lastSender }})</span></p>
      <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="100px">
        <el-form-item label="责任机构:" prop="orgId">
          <el-tree-select
            v-model="temp.orgId"
            class="tree-select"
            :clearable="false"
            :select-params="{
              clearable: false,
              placeholder: '请选择'
            }"
            :tree-params=" {
              'default-expand-all': true,
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgId',
                label: 'orgName',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item label="处理人:" prop="userId">
          <el-select v-model="temp.userId" style="width: 100%;" placeholder="请选择">
            <el-option
              v-for="item in ownersList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户类型:" prop="csmType">
          <el-select v-model="temp.csmType" :disabled="csmTypeDisabled" placeholder="请选择">
            <el-option
              v-for="item in customerTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售员:" prop="saleMan">
          <el-input v-model="temp.saleMan" disabled />
        </el-form-item>
        <el-form-item label="其他:" class="block">
          <el-checkbox v-model="temp.isUrgent">加急</el-checkbox>
          <el-checkbox v-model="temp.isInvoice">需发票</el-checkbox>
        </el-form-item>
        <el-form-item label="客户备注:" prop="csmRemark" class="block">
          <el-input v-model="temp.csmRemark" type="textarea" :rows="3" maxlength="255" show-word-limit />
        </el-form-item>
        <el-form-item label="备注:" prop="remark" class="block">
          <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
        </el-form-item>
        <el-form-item label-width="0">
          <el-checkbox v-if="isOpenGasCheck" v-model="isOpenGasCheck">下达安检任务单</el-checkbox>
          <span v-else>已下达安检任务单</span>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { wechatOrderByExamine, queryOwnerList, queryCsmNearlyOrder, queryCsmGasCheck, queryCsmInfo, queryHasNoCheckOrder } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'

  export default {
    name: 'vetting-orders',
    props: {
      customerTypeMap: {
        Type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        treeData: [],
        currentOrg: null,
        ownersList: [],
        csmTypeDisabled: false,
        isOpenGasCheck: true,
        csmInfo: {},
        overCheck: false, // 超期未安检
        csmType: '', // 原客户类型
        temp: {
          orgId: '',
          userId: '',
          csmType: '',
          isUrgent: false,
          isInvoice: false,
          csmRemark: ''
        },
        appointmentDt: '',
        dateTimeSpare1: '',
        lastOrderInfo: {},
        rules: {
          orgId: [{ required: true, message: '请选择责任机构', trigger: 'change' }],
          userId: [{ required: true, message: '请选择处理人', trigger: 'change' }],
          csmType: [{ required: true, message: '请选择客户类型', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    created() {
      this.getTreeData()
    },
    methods: {
      async open(temp) {
        await Promise.all([this.getHasNoCheckOrder(temp.csmId), this.getCsmInfo(temp.csmCode), this.getCsmNearlyOrder(temp.csmAddressId), this.getGasCheckPlan(temp.csmAddressId), this.getOwnerList(temp.orgId)])
        return new Promise(resolve => {
          this.init(temp)
          this.temp = Object.assign(this.temp, temp)
          if (!temp.userId || temp.userId === 0) this.temp.userId = ''
          if (temp.orgId) this.currentOrg = this.orgList.find(item => item.orgId === temp.orgId)
          this.csmType = temp.csmType
          this.resolve = resolve
          this.visible = true
        })
      },
      init(temp) {
        if ((temp.paymentMethod & 2) > 0) { // 微信支付的用户客户类型不可修改
          this.csmTypeDisabled = true
        }
        let appointStr = ''
        if (temp.appointmentDt) this.appointmentDt = moment(temp.appointmentDt).format('MM-dd HH:mm')
        if (temp.dateTimeSpare1) this.dateTimeSpare1 = moment(temp.dateTimeSpare1).format('MM-dd HH:mm')
        if (this.appointmentDt && this.dateTimeSpare1) {
          appointStr += `, 预约时间：${this.appointmentDt.substring(0, 5)}，${this.appointmentDt.substring(6, 11)}~${this.dateTimeSpare1.substring(6, 11)}`
        } else if (this.appointmentDt) {
          appointStr += `, 预约时间：${this.appointmentDt}之后`
        } else if (this.dateTimeSpare1) {
          appointStr += `, 预约时间：${this.dateTimeSpare1}之前`
        }
        this.$set(this.temp, 'remark', `来自微信${appointStr}`)
      },
      // 获取责任机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询客户
      async getCsmInfo(csmCode) {
        const res = await queryCsmInfo({ csmCode })
        this.csmInfo = res.data
        this.temp.csmRemark = res.data.remark
      },
      async getOwnerList(id) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const orgId = id || this.currentOrg.orgId
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
        const sp1 = this.corpSettingData.sp1
        if (sp1 >> 4 & 0x01) {
          for (const index in res.data) {
            const item = res.data[index]
            if ((item.utype >> 2 & 0x01) > 0) {
              this.$set(this.temp, 'userId', item.userId)
              break
            }
          }
        } else if (sp1 >> 9 & 0x01) {
          if (this.lastOrderInfo && this.lastOrderInfo.lastSenderId > 0) {
            for (const index in res.data) {
              const item = res.data[index]
              if (item.userId === this.lastOrderInfo.lastSenderId) {
                this.$set(this.temp, 'userId', this.lastOrderInfo.lastSenderId)
              }
            }
          }
        }
      },
      // 根据客户地址Id查询客户最近1次订气记录
      async getCsmNearlyOrder(csmAddressId) {
        const res = await queryCsmNearlyOrder({ csmAddressId })
        this.lastOrderInfo = res.data
        if (this.lastOrderInfo.orgId) {
          this.$set(this.temp, 'orgId', this.lastOrderInfo.orgId)
        }
      },
      // 查询客户是否存在未审核的安检单
      async getHasNoCheckOrder(csmId) {
        const res = await queryHasNoCheckOrder({ csmId })
        if (res.data.rows.length > 0) {
          const csmAddress = res.data.rows[0]
          const lastSCheckDt = csmAddress.lastSCheckDt
          // 是否超期未安检
          let overCheck = false
          let lastSCheckDt2

          if (lastSCheckDt) {
            lastSCheckDt2 = moment(lastSCheckDt).valueOf()
            this.dateTimeSpare2 = lastSCheckDt2
          } else {
            lastSCheckDt2 = new Date('1970-01-01')
            this.dateTimeSpare2 = undefined
          }
          switch (csmAddress.limitDays) {
          case -365:
            overCheck = (new Date().getFullYear() - lastSCheckDt2.getFullYear()) >= 1
            break
          case -90:
            if (new Date().getFullYear() - lastSCheckDt2.getFullYear() >= 1) {
              overCheck = true
            } else {
              overCheck = (new Date().getMonth() - lastSCheckDt2.getMonth()) >= 3
            }
            break
          case -30:
            if (new Date().getFullYear() - lastSCheckDt2.getFullYear() >= 1) {
              overCheck = true
            } else {
              overCheck = (new Date().getMonth() - lastSCheckDt2.getMonth()) >= 1
            }
            break
          default:
            overCheck = moment(new Date()).diff(moment(lastSCheckDt2), 'days') > csmAddress.limitDays
            break
          }
          if (overCheck) {
            // 开关：超期未安检提醒
            if ((csmAddress.gasCheckSetOption >> 1 & 0x01) > 0) {
              this.overCheck = true
            }
            if ((this.corpSettingData.sp3 >> 18 & 0x01) > 0) {
              this.isOpenGasCheck = true
            }
          }
        }
      },
      // 查询是否已下达安检任务单
      async getGasCheckPlan(csmAddressId) {
        const res = await queryCsmGasCheck({ csmAddressId })
        // 流程配置开关判断是否开启 下达安检任务单
        if ((this.corpSettingData.sp3 >> 18 & 0x01) > 0) {
          if (res.data === 0) {
            this.isOpenGasCheck = true
          } else {
            this.isOpenGasCheck = false
          }
        }
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      async success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const owner = this.ownersList.find(item => item.userId === this.temp.userId)
          const params = {
            orgId: this.temp.orgId,
            orgSNNo: this.currentOrg.orgSNNo,
            orgName: this.currentOrg.orgName,
            csmId: this.lastOrderInfo.csmId,
            csmName: this.lastOrderInfo.csmName,
            csmCode: this.lastOrderInfo.csmCode,
            csmPhone: this.lastOrderInfo.csmPhone,
            ownerId: this.temp.userId,
            ownerCode: owner.userCode,
            csmAddressId: this.temp.csmAddressId,
            isUrgent: this.temp.isUrgent ? 1 : 0,
            isInvoice: this.temp.isInvoice ? 1 : 0
            // csmType: this.temp.csmType
          }
          // 客户类型变更的时候才传csmType
          // if (this.csmType !== this.temp.csmType) {
          //   params.csmType = this.temp.csmType
          // }
          // params.gasCheck = this.isOpenGasCheck ? 1 : 0
          this.submit(params)
        })
      },
      async submit(params) {
        await wechatOrderByExamine({
          json: params,
          csmType: this.temp.csmType,
          gasCheck: this.isOpenGasCheck ? 1 : 0
        })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.vettingorders {
  position: relative;
  .desc {
    margin-bottom: 10px;
  }
  .status-img {
    position: absolute;
    right: 20px;
  }
}
.tree-select {
  width: 100%;
  & /deep/ .el-tree-select-input {
    width: 100%;
  }
}
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
